package service

import (
	"encoding/json"
	"fmt"
	"usplatformserver/internal/model"
	"usplatformserver/pkg/zmq"
)

// 设置阈值消息请求
type setThresholdMsgReq struct {
	MsgType uint32                `json:"msgType"`
	Data    []model.ThresholdInfo `json:"data"`
}

// 设置LVEF阈值消息请求
type setLVEFThresholdMsgReq struct {
	MsgType uint32                   `json:"msgType"`
	Data    *model.ThresholdLVEFInfo `json:"data"`
}

// 获取阈值
func (svc *Service) GetThreshold(addr string) ([]model.ThresholdInfo, error) {
	msgStr, err := json.Marshal(zmq.MsgGetThreshold)
	if err != nil {
		fmt.Println("json.Marshal failed: ", err)
		return nil, err
	}

	rcvMsg, err := zmq.SendMessage(addr, string(msgStr))
	var rcv []model.ThresholdInfo
	err = json.Unmarshal([]byte(rcvMsg), &rcv)
	if err != nil {
		fmt.Println("json.Unmarshal failed: ", err)
		return nil, err
	}

	return rcv, nil
}

// 设置阈值
func (svc *Service) SetThreshold(addr, thresholds string) error {
	var thresholdsTmp model.ThresholdList
	//解析输入
	err := json.Unmarshal([]byte(thresholds), &thresholdsTmp)
	if err != nil {
		fmt.Println("json.Unmarshal failed: ", err)
		return err
	}
	//重组zmq消息
	msgReq := setThresholdMsgReq{
		MsgType: zmq.MsgSetThreshold.MsgType,
		Data:    thresholdsTmp.List,
	}
	msgReqStr, err := json.Marshal(msgReq)
	if err != nil {
		fmt.Println("json.Marshal(msgReq) failed: ", err)
		return err
	}
	//发送设置阈值消息
	_, err = zmq.SendMessage(addr, string(msgReqStr))
	if err != nil {
		fmt.Println("zmq.SendMessage failed: ", err)
		return err
	}

	return nil
}

// 获取LVEF自动保存阈值
func (svc *Service) GetLVEFThreshold(addr string) (*model.ThresholdLVEFInfo, error) {
	msgStr, err := json.Marshal(zmq.MsgGetLVEFThreshold)
	if err != nil {
		fmt.Println("json.Marshal failed: ", err)
		return nil, err
	}

	rcvMsg, err := zmq.SendMessage(addr, string(msgStr))
	var rcv *model.ThresholdLVEFInfo
	err = json.Unmarshal([]byte(rcvMsg), &rcv)
	if err != nil {
		fmt.Println("json.Unmarshal(thresholdLVEFInfo) failed: ", err)
		return nil, err
	}

	return rcv, nil
}

// 设置LVEF阈值
func (svc *Service) SetLVEFThreshold(addr, lvef string) error {
	var lvefTmp model.ThresholdLVEFInfo
	//解析输入
	err := json.Unmarshal([]byte(lvef), &lvefTmp)
	if err != nil {
		fmt.Println("json.Unmarshal lvef failed: ", err)
		return err
	}
	//重组zmq消息
	msgReq := setLVEFThresholdMsgReq{
		MsgType: zmq.MsgSetLVEFThreshold.MsgType,
		Data:    &lvefTmp,
	}
	msgReqStr, err := json.Marshal(msgReq)
	if err != nil {
		fmt.Println("json.Marshal(msgSetLVEFThreshold) failed: ", err)
		return err
	}
	//发送设置阈值消息
	_, err = zmq.SendMessage(addr, string(msgReqStr))
	if err != nil {
		fmt.Println("zmq.SendMessage LVEF failed: ", err)
		return err
	}

	return nil
}
